﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mime;
using System.Reflection;
using System.Text;
using System.Web;
using EPiServer;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.Filters;
using EPiServer.ServiceLocation;

namespace EPiBoost.Core.Handlers
{
	public class PageTypeThumbnailHandler : IHttpHandler
	{
		internal static string GetPath(Type type)
		{
			if (Configuration.Core.Handlers.PageTypeThumbnailHandler.Enabled)
			{
				string url = "/EPiBoost/PageTypeThumbnailHandler/" + type.FullName + "," + type.Assembly.GetName().Name + ".ptthumb";
				if (HttpContext.Current != null)
				{
					return System.Web.Mvc.UrlHelper.GenerateContentUrl("~" + url, new HttpContextWrapper(HttpContext.Current));
				}
				return "../.." + url;
			}
			return "404.jpg";
		}

		public bool IsReusable
		{
			get { return false; }
		}

		public void ProcessRequest(HttpContext context)
		{
			string url = context.Request.RawUrl;
			
			string typeFullName = url.Substring(url.LastIndexOf('/')+1);
			typeFullName = typeFullName.Substring(0, typeFullName.LastIndexOf('.'));
			  
			var type = Type.GetType(typeFullName);

			if (type != null)
			{
				var ptr = ServiceLocator.Current.GetInstance<PageTypeRepository>();
				var pt = ptr.Load(type);
				if (pt != null)
				{
					var page = GetFirstPageOfType(pt);
					if(page!=null)
					{
						WriteThumbnail(page, context);
						return;
					} 
				}
			}

			context.Response.StatusCode = (int)HttpStatusCode.NotFound;
		}

		private void WriteThumbnail(PageData page, HttpContext context)
		{
			Bitmap thumb = null;
			int bw = Configuration.Core.Handlers.PageTypeThumbnailHandler.BrowserWidth;
			int bh = Configuration.Core.Handlers.PageTypeThumbnailHandler.BrowserHeight; 
			int tw = 120;  
			int th = 90;
			
			var url = new UrlBuilder(context.Request.Url);
			url.Path = page.LinkURL;

			context.Response.ContentType = "image/jpeg";

			// return context bitmap
			thumb = Helpers.WebPageThumbnail.GetWebSiteThumbnail(url.ToString(), bw, bh, tw, th);
			
			thumb.GetThumbnailImage(tw, th, null, IntPtr.Zero).Save(context.Response.OutputStream, ImageFormat.Jpeg);

			thumb.Dispose();
		}

		private static PageData GetFirstPageOfType(PageType pt)
		{
			var contentLoader = ServiceLocator.Current.GetInstance<IContentLoader>();

			var start = contentLoader.Get<PageData>(PageReference.StartPage);
			var langBranch = start.LanguageBranch;
			var languageSelector = LanguageSelector.Fallback(langBranch, true);

			var criterias = new PropertyCriteriaCollection();
			var c = new PropertyCriteria();
			c.Condition = CompareCondition.Equal;
			c.Name = "PageTypeID";
			c.Type = PropertyDataType.PageType;
			c.Value = pt.ID.ToString();
			c.Required = true;
			criterias.Add(c); 

			var pages = DataFactory.Instance.FindAllPagesWithCriteria(PageReference.RootPage, criterias, langBranch, languageSelector);

			return pages.OrderByDescending(d=>d.Saved).FirstOrDefault();
		}
	}
}
